package test;

import ch.qos.logback.classic.Logger;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.mybatis.wrap.MybatisSqlSessionFactoryBuilder;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.util.Properties;

/**
 * 数据库持久化映射处理类，全局单例
 *
 * @author zhoukai
 */
public class Mybatis {

    private SqlSessionFactory sqlSessionFactory;
    private static final Mybatis instance = new Mybatis();

    private final Logger logger = (Logger) LoggerFactory.getLogger(Mybatis.class);

    private InputStream getConfig() {
        URL url = Thread.currentThread().getContextClassLoader().getResource("");
        String protocol = url.getProtocol();
        String path = url.getPath();
        if (!protocol.equals("file")) {
            File file = new File(path);
            file = file.getParentFile();
            path = file.getPath();
        }
        if (path.charAt(0) == '/') path = path.substring(1);
        int pathLastCharIdx = path.length() - 1;
        if (path.charAt(pathLastCharIdx) == '/') path = path.substring(0, pathLastCharIdx);
        if (logger.isDebugEnabled()) logger.debug("配置文件加载主路径：" + path);
        File file = new File(path + "/sys-config/db.properties");
        InputStream is = null;
        try {
            is = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            logger.error(e.getLocalizedMessage(), e);
        }
        return is;
    }

    /**
     * 私有构造方法，不允许外部创建对象
     */
    private Mybatis() {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        try (InputStream is = Resources.getResourceAsStream(classLoader, "mybatis3-config.xml")) {
            Properties dbProps = new Properties();
            try (InputStream dbPropsStream = getConfig()) {
                dbProps.load(dbPropsStream);
            }
            if (!dbProps.isEmpty()) {
                sqlSessionFactory = new MybatisSqlSessionFactoryBuilder().build(is, "hikari", dbProps);
            } else {
                sqlSessionFactory = new MybatisSqlSessionFactoryBuilder().build(is);
            }
        } catch (IOException ex) {
            logger.error("无法读取mybatis3-config.xml配置", ex);
        }
    }

    /**
     * 获取全局唯一实例
     *
     * @return 唯一实例
     */
    public static Mybatis getInstance() {
        return instance;
    }

    /**
     * 获取数据库操作管道
     *
     * @return
     */
    public synchronized SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }
}

